/**
 * 
 */
package com.easidea.tim.dao.base;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Restrictions;
import org.springside.core.dao.extend.HibernateEntityExtendDao;

import com.easidea.tim.entity.base.FlowNo;
import com.easidea.tim.util.NumberUtil;
import com.easidea.tim.util.TimConstant.FlowNoType;

/**
 * @author Harrison
 *
 */
public class FlowNoDao extends HibernateEntityExtendDao<FlowNo> {

	public String genNextFlowNo(FlowNoType type) {
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        return date + "-" + type.getFlowNoKey() + "-" + NumberUtil.toString(genNextValue(type, date), 4);
    }

    private Long genNextValue(FlowNoType type, String encodeKey) {

        synchronized (type) {
            Criteria criteria = createUnDeletedCriteria();
            criteria.setLockMode(LockMode.UPGRADE);
            criteria.add(Restrictions.eq("type", type));
            criteria.add(Restrictions.eq("key", encodeKey));
            List<FlowNo> list = criteria.list();

            FlowNo flowNo;
            long currentValue;
            if (list.size() == 0) {
                flowNo = new FlowNo();
                flowNo.setType(type);
                flowNo.setKey(encodeKey);
                flowNo.setNextValue(2L);
                currentValue = 1L;
            } else {
                flowNo = list.get(0);
                currentValue = flowNo.getNextValue();
                flowNo.setNextValue(currentValue + 1);
            }
            save(flowNo);
            return currentValue;
        }
    }
	
}
